# -*- coding: utf-8 -*-
"""
Created on Tue Oct 01 16:25:04 2013

@author: Maxim
"""
from numpy import linspace, cos
import performance
import aircraft

class ClimbResult:
    def __init__(self):
        self.range = 0.0
        self.time  = 0.0
        self.fuelBurned = 0.0
    
    def display(self):
        print 'Range to climb = %.2fm'%self.range
        print 'Time to climb  = %.2fsec'%self.time
        print 'Fuel burned    = %.2fkg'%(self.fuelBurned/9.81)

def climb_simulation(aircraft,startAltitude,endAltitude,powerSetting=100.,nSeg=10,disp=False):
    """
    Simulation of climb flight
    
    Parameters
    ----------
    
    aircraft : object
        aircraft object
    startAltitude : float
        altitude where climb starts
    endAltitude : float
        climb end altitude
    powerSetting : float
        engine power setting [0,100]
    nSeg : integer
        number of altitude segments to perform integration
    disp : bool
        displays information at all steps of integration
    
    Note
    ----

    if end altitude is too high or engine power setting is too low then 
    negative maximum rate of climb may occur that will cause wrong results.
    """
    clm = performance.climbAndDescendingFlight()
    Cd0 = aircraft.get_drag()
    Clmax = 1.8
    altitude = linspace(startAltitude,endAltitude,nSeg)
    dh = altitude[1] - altitude[0]
    time, distance, fuelWeight = 0., 0., 0.
    V = 50.0
    for h in altitude[:-1]:
        aircraft.analysis.aerodynamics.update(V,1.225)
        tm       =aircraft.analysis.thrust
        k        =aircraft.analysis.aerodynamics.results.k
        Cd0      =aircraft.analysis.aerodynamics.results.Cd0
        S        =aircraft.wing.area
        mass     =aircraft.mass.totalMass
        bi  =performance.basicInput(h,0,Cd0,k,S,mass,Clmax)
        clm.run_maximumClimbRate(bi,tm,powerSetting)
        dt = dh / clm.climbRate
        dwf= bi.g*dt*clm.fuelFlow
        ds = clm.velocity * cos(clm.climbAngle) * dt
        V = clm.velocity
        time       += dt
        distance   += ds
        fuelWeight += dwf
        if disp:
            print 'dh = %.2f\tdt = %.2f\tdw = %.2f\tds = %.2f\tR/C = %.2f\ttheta = %.2f'%(dh,dt,dwf,ds,clm.climbRate,clm.climbAngle)
    rslt = ClimbResult()
    rslt.range = distance
    rslt.fuelBurned = fuelWeight
    rslt.time = time
    return rslt


def run_test():
    ac = aircraft.load('V0510')
    climb_simulation(ac,0,2000,100.,21).display()
    climb_simulation(ac,0,2000,0.0,21).display()

if __name__=="__main__":
    run_test()